﻿using System;
using System.Web;
using System.IO;
using FShare.Helpers;

namespace FShare.Classes
{
    public class FileService
    {
        private FileService()
        {
        }

        public static string SaveFile(HttpPostedFileBase postedFile)
        {
            if (postedFile == null || string.IsNullOrEmpty(postedFile.FileName))
            {
                throw new ArgumentNullException("postedFile");
            }

            if (postedFile.InputStream == null)
            {
                throw new NullReferenceException();
            }

            string relativeFilePath = Path.Combine(Constants.FILE_SAVING_PATH, Utils.GenerateFolderName());
            string dirPath = HttpContext.Current.Server.MapPath(relativeFilePath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
        
            // replace blank places with dashes
            string fileName = postedFile.FileName.Replace(' ', '-');
            fileName = Path.Combine(dirPath, fileName);
            postedFile.SaveAs(fileName);

            return Path.Combine(relativeFilePath, postedFile.FileName);
        }

        public static bool DeleteFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new NullReferenceException();
            }

            string absouluteFilePath = HttpContext.Current.Server.MapPath(Path.Combine(Constants.FILE_SAVING_PATH, path));
            if (!File.Exists(absouluteFilePath))
            {
                return false;
            }

            try
            {
                File.Delete(absouluteFilePath);
                absouluteFilePath = Path.GetDirectoryName(absouluteFilePath);
                Directory.Delete(absouluteFilePath);
                return true;
            }
            catch (IOException)
            {
                return false;
            }
        }
    }
}
